package zouran.filepractice.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

/**
 * 文件上传
 * Author：zouran
 * Date：2023/4/29  16:07
 */
@RestController
@RequestMapping("/upload")
public class UploadFile {
    /**
     *文件的存储，接收前端上传的文件
     */
    @RequestMapping("/file")
    public String uploadFile(MultipartFile[] fileList) throws IOException {
        //依次存每个文件
        for (MultipartFile file:fileList)
        {   //获取文件后缀
            String[] list = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
            String suffix = "." + list[list.length - 1];
            //生成文件uuid前缀
            String prefix = String.valueOf(UUID.randomUUID());
            //存储路径
            String baseUrl = "D:\\study\\upload\\" + setFilePath();
            //新建文件夹失败
            if (!new File(baseUrl).exists() && !new File(baseUrl).mkdirs())
                return "error";
            //创建输出流
            OutputStream outputStream = new FileOutputStream(baseUrl + prefix + suffix, true);
            //写入到指定目录
            outputStream.write(file.getBytes());
            outputStream.close();
        }
        return "success";
    }
    //本地文件拷贝
    public void localFileCopy() throws IOException {
        //要拷贝的文件位置
        String localUrl="D:\\study\\1.png";
        File file=new File(localUrl);
        //创建输入流
        InputStream inputStream=new FileInputStream(file);
        //文件后缀
        String[] list=Objects.requireNonNull(file.getName()).split("\\.");
        String suffix= "."+list[list.length-1];
        //uuid前缀
        String prefix= String.valueOf(UUID.randomUUID());
        //目标路径
        String baseUrl="D:\\study\\"+setFilePath();
        //路径不存在且创建失败
        if(!new File(baseUrl).exists()&&!new File(baseUrl).mkdirs()) System.out.println("error");
        //创建输出流
        OutputStream outputStream=new FileOutputStream(baseUrl+prefix+suffix,true);
        byte[] bytes=new byte[1024];
        int length;
        //利用字节流写入
        while ((length=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,length);
        }
        //关闭文件流
        inputStream.close();
        outputStream.close();
    }
    //以时间为文件夹生成文件存储路径(三级目录)，例如:2023//2023-4//2023-4-29
    public String setFilePath(){
        LocalDateTime localDateTime=LocalDateTime.now();
        String year= String.valueOf(localDateTime.getYear());
        String month=year+"-"+localDateTime.getMonthValue();
        String day=month+"-"+localDateTime.getDayOfMonth();
        return year+"\\"+month+"\\"+day+"\\";
    }
}
